const app = getApp();
const log = require('./log');
const ws = require('./websocket');
const TEST_ACCOUNT = require('../../account');
const uuid = require('../../../../components/trtc-room/utils/uuid');
const TAG_NAME = "VR-COMMON";

const data = {
  sdkAppId: TEST_ACCOUNT.sdkappid,
};

module.exports = {
  /**
   * 是否通过ws发送log日志
   */
  async ifSendLogMsg() {
    await new Promise((resolve, reject) => {
      wx.request({
        url: data.serviceUrl + '/miniProgram/isLogger',
        method: 'GET',
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          app.globalData.ifSendLog = res.data.body;
          resolve(res);
        },
        fail(res) {
          log.debug(TAG_NAME, "获取远端信息异常", res)
          // 若请求失败 默认发送
          app.globalData.ifSendLog = true;
          reject(res)
        }
      })
    })
  },

  /**
   * 处理参数进房
   * @param {*} options 
   */
  async enterRoom(options) {
    // 格式化参数
    this.formatParam(options);
    // 登录
    await this.login();
    // 校验是否需要通过ws发送日志
    await this.ifSendLogMsg();
    return data;
  },

  /**
   * 参数格式化
   * @param {*} options 参数值
   */
  formatParam(options) {
    let {
      agentId,
      agentName,
      roomID,
      type,
      msg,
      toolMsg,
      exitMode,
      customerId,
      productId
    } = options;
    let serviceUrl = null;
    let enterType = 3;
    let userToken = null;

    const accountInfo = wx.getAccountInfoSync();
    const version = accountInfo.miniProgram.envVersion
    if (version === 'develop') {
      console.log('开发版');
    } else if (version === 'trial') {
      console.log('体验版');
    } else if (version === 'release') {
      console.log('正式版');
    }

    if (agentId) {
      if (!agentName) {
        agentName = '理财经理'
      }
      enterType = 0;
      exitMode = '0';
      roomID = uuid.wxuuid();
    } else if (roomID) {
      enterType = 1;
      exitMode = '1';
    }

    if (accountInfo.miniProgram.appId === 'wx94d9939e806c86cd') {
      // 太保sit环境后台
      serviceUrl = "https://hkt-sit.cpic.com.cn/vrhelper";
    } else if (accountInfo.miniProgram.appId === 'wx1544133dfa2e710f') {
      // 太保生产环境后台
      serviceUrl = "https://hkt.cpic.com.cn/vrhelper";
    } else {
      // 公司环境后台
      // appId wx7f92d1bbad252b41
      serviceUrl = "https://www.rdata.top/vrhelper";
      // serviceUrl = "http://127.0.0.1:18080/vrhelper";
      if (enterType === 3) {
        enterType = 0;
      }
      if (!roomID) {
        roomID = uuid.wxuuid();
      }
      userToken = 'hytest';
      exitMode = '1';
      if (!agentName) {
        agentName = '理财经理'
      }
    }

    data.agentId = agentId;
    data.roomID = roomID;
    data.serviceUrl = serviceUrl;
    data.enterType = enterType;
    data.imgUrl = serviceUrl + '/haoyi/image';
    data.type = type;
    data.msg = msg;
    data.toolMsg = toolMsg;
    data.exitMode = exitMode;
    data.customerId = customerId ? customerId : "";
    data.productId = productId ? productId : "";
    data.userToken = userToken;
    data.agentName = agentName;
  },

  /**
   * 登录
   */
  async login() {
    // 加载逻辑调整
    let self = this;
    //授权登录，获取用户openId
    await new Promise((resolve) => {
      wx.login({
        success(res) {
          if (res.code) {
            console.log('用户已登录')
            data.jsCode = res.code;
            self.resolve = resolve;
            // 获取用户openid
            self.getOpenId()
          } else {
            log.debug(TAG_NAME, '登录失败！' + res.errMsg)
            self.showError('网络异常')
          }
        },
        fail() {
          self.showError('网络异常')
        }
      })
    })
  },

  /**
   * 获取用户openId
   */
  getOpenId() {
    let self = this;
    if (data.openId) {
      self.hasPermission();
      return
    }
    wx.request({
      url: data.serviceUrl + '/sign/getUserOpenId',
      data: {
        jsCode: data.jsCode
      },
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        log.debug(TAG_NAME, "请求获取openId成功", res.data)
        data.openId = res.data.body;
        // 查询用户是否授权
        self.hasPermission()
      },
      fail(res) {
        log.debug(TAG_NAME, "请求获取openId失败", res)
        self.showError('网络异常')
      }
    })
  },

  /**
   * 查询用户是否授权
   */
  hasPermission() {
    const self = this;
    wx.request({
      url: data.serviceUrl + '/user/query',
      data: {
        userId: data.openId
      },
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.body) {
          // 已授权不再走获取头像流程
          app.globalData.userDetailInfo = {
            nickName: decodeURIComponent(res.data.body.userName),
            avatarUrl: data.serviceUrl + '/user/image/' + res.data.body.userId,
          }
          data.hasUserInfo = true;
          console.log('用户已授权', res.data.body, app.globalData.userDetailInfo)
        } else {
          // 没授权
          app.globalData.userDetailInfo = null;
          data.hasUserInfo = false;
          console.log('未授权')
        }
        // 初始化数据
        self.initData();
      },
      fail(res) {
        log.debug(TAG_NAME, "获取远端信息异常", res)
        // 发生异常认为没授权
        app.globalData.userDetailInfo = null;
        data.hasUserInfo = false;
        self.setInitReady();
        console.log('未授权')
      }
    })
  },

  /**
   * 初始化数据
   */
  initData() {
    if (data.type && data.type === 'hangup') {
      console.log('挂断后回退')
      // 客户端会退出小程序，理财经理返回上一级页面，不应该抛出异常
      this.showError(data.msg, data.toolMsg);
    } else if ((data.agentId && data.agentId !== 'undefined') || (data.roomID && data.roomID !== 'undefined')) {
      data.showModal = false;
      data.isShare = false;
      this.checkUrlSupport();
    } else {
      this.showError('您当前入口不正确', '请联系您的理财经理');
    }
  },

  /**
   * 初始化ws连接
   * @param callback 接收到消息调用的方法
   */
  initWebsocket(callback) {
    const {
      wsUrl,
      roomID,
      openId
    } = data;
    const websocketUrl = `${decodeURIComponent(wsUrl)}/notice/${roomID}/${openId}`;
    // 初始化ws
    ws.initWS(websocketUrl, callback);
  },

  /**
   * 校验访问的url
   */
  checkUrlSupport() {
    let wrapUrl = data.serviceUrl + "/haoyi/index.html";
    let wsUrl = data.serviceUrl.replace("https", "wss").replace("http", "ws");
    data.wrapUrl = wrapUrl;
    data.wsUrl = encodeURIComponent(wsUrl);
    data.debugType = '';
    // 获取userSign
    this.getUserSign()
  },

  /**
   * 获取用户的userSig
   */
  getUserSign() {
    let self = this;
    wx.request({
      url: data.serviceUrl + '/sign/getUserSign',
      data: {
        sdkAppId: data.sdkAppId,
        userId: data.openId,
      },
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      async success(res) {
        log.debug(TAG_NAME, "请求获取userSig成功", res.data)
        data.userSign = res.data.body;
        // 入口为小程序 创建房间
        if (data.enterType === 0 && data.roomID) {
          // 创建房间
          const result = await self.createGroup();
          console.log(TAG_NAME, 'create result ===', result)
          if (result !== 'success') {
            // 创建房间不成功 直接退出
            data.roomID = '-1';
            self.showError("会话已结束，请联系理财经理重新建立");
          }
        }
        self.setInitReady()
        self.resolve();
      },
      fail() {
        log.debug(TAG_NAME, "请求获取userSig失败")
        self.showError('网络异常');
        reject()
      }
    })
  },

  /**
   * 建群
   * @return {*}
   */
  async createGroup() {
    // 测试时直接跳转
    // return 'success';
    const p = await new Promise(resolve => {
      wx.request({
        url: data.serviceUrl + '/room/add',
        data: {
          createId: data.openId,
          roomId: data.roomID
        },
        method: 'POST',
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          if (res.data.success) {
            data.role = '0';
            resolve('success')
          } else {
            resolve('error')
          }
        },
        fail() {
          log.debug(TAG_NAME, "请求创建失败")
          resolve('error')
        }
      })
    });
    log.debug(TAG_NAME, p);
    return p;
  },

  /**
   * 设置初始化成功状态
   */
  setInitReady() {
    data.initReady = true;
    // this.hideLoad()
  },

  /**
   * 统一错误处理
   * @param {*} msg 
   * @param {*} toolMsg
   * @param {*} error 
   */
  showError(msg, toolMsg, error) {
    log.error(TAG_NAME, 'Error msg:', msg || error);
    wx.redirectTo({
      url: '/pages/tic/room_webview/index/index?type=hangup&exitMode=' + data.exitMode + '&msg=' + msg + '&toolMsg=' + toolMsg,
    })
  },
}